package cn.hls.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.hls.entity.User;
import cn.hls.until.GenericsUtils;

public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {
	//定义请求的controler类
    private static List<String> controllers=new ArrayList<String>();
    private static List<String> methods=new ArrayList<String>();
    static{
    	controllers.add("MemberController");
    	controllers.add("CardController");
    	controllers.add("AreaController");
    	methods.add("add");
    	methods.add("update");
    	methods.add("active");
    }
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		User user = (User) request.getSession().getAttribute("currentUser");
		if (user == null) {
			//获取请求的方法
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			//获取请求controller类的名称
			String requestController=handlerMethod.getBeanType().getSimpleName();
			String requestMethod=handlerMethod.getMethod().getName();
			//当请求的Controller类及请求相同时
			if(controllers.contains(requestController)&& methods.contains(requestMethod)){
				String requestSystem=request.getParameter("reqsys");
				String token=request.getParameter("token");
				if(StringUtils.hasText(requestSystem)){//请求系统来源信息存在时
					int len=requestSystem.indexOf('_');
					String salt=requestSystem.substring(len+1);
					String sys=requestSystem.substring(0,len);
					//密文存在时
					if(StringUtils.hasText(token)){
						if(requestSystem.equalsIgnoreCase(GenericsUtils.encrypt(sys+"_"+requestMethod, salt))){
							return true;
						}else{
							response.getWriter().write("操作失败");
							return false;
						}
					}else{
						response.getWriter().write("操作失败");
						return false;
					}
				}else{
					response.getWriter().write("操作失败");
					return false;
				}
			}else{
				if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ //如果是ajax请求响应头会有，x-requested-with  
					response.setStatus(600);
		            response.setHeader("sessionstatus", "timeout");//在响应头设置session状态  {
				}else{
					response.sendRedirect(request.getContextPath() + "/login.jsp");
				}
				return false;
			}
		}
		return true;

	}

}
